import React, { useState, useEffect, useRef } from "react";
import { message } from "antd";
import * as Skeleton from "react-loading-skeleton";
import "react-loading-skeleton/dist/skeleton.css";
import Workspace from "@/models/workspace";
import ManageWorkspace, {
  useManageWorkspaceModal,
} from "../../Modals/ManageWorkspace";
import RenameModals from "@/components/Modals/RenameModals";
import NewSessionModal, { useNewSessionModal } from "../../Modals/NewSession";
import RemoveModals, { useRemoveModal } from "../../Modals/RemoveModals";
import paths from "@/utils/paths";
import { useParams, useNavigate } from "react-router-dom";
// import { GearSix, UploadSimple, DotsSixVertical } from "@phosphor-icons/react";
import useUser from "@/hooks/useUser";
import ThreadContainer from "./ThreadContainer";
import { useMatch } from "react-router-dom";
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
import showToast from "@/utils/toast";
import "../index.css";
import Dot from "@/media/sidebar/dot.png";
import DotActive from "@/media/sidebar/dot-active.png";
import Plus from "@/media/sidebar/plus.png";
import PlusActive from "@/media/sidebar/plus-active.png";
import Share from "@/media/sidebar/share.png";
import ShareActive from "@/media/sidebar/share-active.png";
import Arrow from "@/media/sidebar/arrow.png";
import ModalWorkspaceSet from "../../ModalWorkspaceSet";

export default function ActiveWorkspaces() {
  const navigate = useNavigate();
  const { user } = useUser();
  const { slug, threadSlug = null } = useParams();
  const [loading, setLoading] = useState(true);
  const [workspaces, setWorkspaces] = useState([]);
  const [selectedWs, setSelectedWs] = useState(null);
  const [isOn, setIsOn] = useState(-1);
  const [workspaceItem, setWorkspaceItem] = useState();
  const [showOptions, setShowOptions] = useState(-1);
  const [threads, setThreads] = useState([]);
  const { showing, showModal, hideModal } = useManageWorkspaceModal();
  const { showingSession, showSessionModal, hideSessionModal } = useNewSessionModal();
  const { showingRemove, showRemoveModal, hideRemoveModal } = useRemoveModal();
  const isInWorkspaceSettings = !!useMatch("/workspace/:slug/settings/:tab");
  const optionsContainer = useRef(null);
  async function getWorkspaces() {
    const workspaces = await Workspace.all();
    setLoading(false);
    setWorkspaces(Workspace.orderWorkspaces(workspaces));
  }

  useEffect(() => {
    getWorkspaces();
  }, []);
  if (loading) {
    return (
      <Skeleton.default
        height={40}
        width="100%"
        count={5}
        baseColor="var(--theme-sidebar-item-default)"
        highlightColor="var(--theme-sidebar-item-hover)"
        enableAnimation={true}
        className="my-1"
      />
    );
  }
  /**
   * Reorders workspaces in the UI via localstorage on client side.
   * @param {number} startIndex - the index of the workspace to move
   * @param {number} endIndex - the index to move the workspace to
   */
  function reorderWorkspaces(startIndex, endIndex) {
    const reorderedWorkspaces = Array.from(workspaces);
    const [removed] = reorderedWorkspaces.splice(startIndex, 1);
    reorderedWorkspaces.splice(endIndex, 0, removed);
    setWorkspaces(reorderedWorkspaces);
    const success = Workspace.storeWorkspaceOrder(
      reorderedWorkspaces.map((w) => w.id)
    );
    if (!success) {
      showToast("Failed to reorder workspaces", "error");
      Workspace.all().then((workspaces) => setWorkspaces(workspaces));
    }
  }

  const onDragEnd = (result) => {
    if (!result.destination) return;
    reorderWorkspaces(result.source.index, result.destination.index);
  };

  const toggleSwitch = (e, workspace) => {
    if (e.target === e.currentTarget) {
      if (isOn == workspace.id) {
        setIsOn(-1);
      } else {
        setIsOn(workspace.id);
      }
    }
  };

  // 删除工作区
  const removeThread = (threadId) => {
    setThreads((prev) =>
      prev.map((_t) => {
        if (_t.id !== threadId) return _t;
        return { ..._t, deleted: true };
      })
    );

    // Show thread was deleted, but then remove from threads entirely so it will
    // not appear in bulk-selection.
    setTimeout(() => {
      setThreads((prev) => prev.filter((t) => !t.deleted));
    }, 500);
  };
  return (
    <DragDropContext onDragEnd={onDragEnd}>
      <Droppable droppableId="workspaces">
        {(provided) => (
          // 工作区容器
          <div
            role="list"
            aria-label="Workspaces"
            className="flex flex-col gap-y-[20px] workspaces overflow-y-auto h-[calc(100%-100px)]"
            ref={provided.innerRef}
            {...provided.droppableProps}
          >
            {workspaces.map((workspace, index) => {
              const isActive = workspace.slug === slug;
              return (
                <Draggable
                  key={workspace.id}
                  draggableId={workspace.id.toString()}
                  index={index}
                  isDragDisabled={user?.role === "default"}
                >
                  {(provided, snapshot) => (
                    // 工作区列表
                    <div
                      ref={provided.innerRef}
                      {...provided.draggableProps}
                      className={`flex flex-col w-full group ${
                        snapshot.isDragging ? "opacity-50" : ""
                      }`}
                      role="listitem"
                    >
                      {/* 工作区列表 */}
                      <div className="flex gap-x-2 items-center justify-between space-list relative">
                        <a
                          aria-current={isActive ? "page" : ""}
                          className={`
                            transition-all duration-[200ms] 
                            flex flex-grow gap-x-2 text-white justify-start items-center
                          `}
                        >
                          <div className="flex flex-row justify-between w-full items-center">
                            {/* 工作区名称 */}
                            <div
                              className="flex items-center overflow-hidden flex-grow"
                              onClick={(e) => {
                                e.stopPropagation();
                                toggleSwitch(e, workspace);
                              }}
                            >
                              <span
                                className={`
                                text-[14px] font-semibold space-span whitespace-nowrap overflow-hidden text-white truncate
                              `}
                              >
                                {workspace.name}
                              </span>
                              <img
                                src={Arrow}
                                alt="Arrow"
                                className={`w-[16px] mx-[0px] group-hover:duration-200 ${isOn == workspace.id ? "" : "arrow-up"}`}
                              />
                            </div>

                            {user?.role !== "default" && (
                              <div
                                {...provided.dragHandleProps}
                                className="cursor-grab mr-[3px]"
                              >
                                {/* <DotsSixVertical
                                  size={20}
                                  color="var(--theme-sidebar-item-workspace-active)"
                                  weight="bold"
                                /> */}
                                {/* <img
                                  src={PlusActive}
                                  alt="PlusActive"
                                  className="w-[16px] mx-[0px] hover-image group-hover:duration-200"
                                /> */}
                              </div>
                            )}

                            {/* 工作区悬浮提示工具       */}
                            {user?.role !== "default" && (
                              <div
                                ref={optionsContainer}
                                className={`flex items-center gap-x-[2px] transition-opacity duration-200`}
                              >
                                <button
                                  type="button"
                                  onClick={(e) => {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    showSessionModal();
                                    setWorkspaceItem(workspace);
                                  }}
                                  className="border-none flex items-center justify-center ml-auto"
                                >
                                  {/* <UploadSimple className="h-[20px] w-[20px]" /> */}
                                  <img
                                    src={Plus}
                                    alt="Plus"
                                    className="w-[16px] mx-[0px] default-image group-hover:duration-200"
                                  />
                                  <img
                                    src={PlusActive}
                                    alt="PlusActive"
                                    className="w-[16px] mx-[0px] hover-image group-hover:duration-200"
                                  />
                                </button>

                                <button
                                  // onClick={(e) => {
                                  //   e.preventDefault();
                                  //   e.stopPropagation();
                                  //   navigate(
                                  //     isInWorkspaceSettings
                                  //       ? paths.workspace.chat(workspace.slug)
                                  //       : paths.workspace.settings.generalAppearance(
                                  //           workspace.slug
                                  //         )
                                  //   );
                                  // }}
                                  onClick={(e) => {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    setSelectedWs(workspace);
                                    showModal();
                                  }}
                                  className="flex items-center justify-center text-[#A7A8A9] ml-auto px-[8px]"
                                  aria-label="General appearance settings"
                                >
                                  {/* <GearSix
                                    color={
                                      isInWorkspaceSettings &&
                                      workspace.slug === slug
                                        ? "#46C8FF"
                                        : undefined
                                    }
                                    className="h-[20px] w-[20px]"
                                  /> */}
                                  <img
                                    src={Share}
                                    alt="Share"
                                    className="w-[16px] mx-[0px] default-image group-hover:duration-200"
                                  />
                                  <img
                                    src={ShareActive}
                                    alt="ShareActive"
                                    className="w-[16px] mx-[0px] hover-image group-hover:duration-200"
                                  />
                                </button>

                                <button
                                  type="button"
                                  onClick={(e) => {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    setSelectedWs(workspace);
                                    setShowOptions(workspace.id);
                                  }}
                                  className="border-none flex items-center justify-center ml-auto text-[#A7A8A9]"
                                >
                                  {/* <UploadSimple className="h-[20px] w-[20px]" /> */}
                                  <img
                                    src={Dot}
                                    alt="Dot"
                                    className="w-[16px] mx-[0px] default-image group-hover:duration-200"
                                  />
                                  <img
                                    src={DotActive}
                                    alt="DotActive"
                                    className="w-[16px] mx-[0px] hover-image group-hover:duration-200"
                                  />
                                </button>

                                {/* 悬浮工具提示 */}
                                {showOptions == workspace.id && (
                                  <OptionsMenu
                                    containerRef={optionsContainer}
                                    workspace={workspace}
                                    onRemove={showRemoveModal}
                                    close={() => setShowOptions(-1)}
                                    currentThreadSlug={threadSlug}
                                    getWorkspaces={getWorkspaces}
                                  />
                                )}
                              </div>
                            )}
                          </div>
                        </a>
                      </div>
                      {/* 会话列表 */}
                      {workspace.id == isOn && (
                        <ThreadContainer
                          workspace={workspace}
                          isActive={isActive}
                        />
                      )}
                    </div>
                  )}
                </Draggable>
              );
            })}
            {provided.placeholder}
            {/* 上传文件弹窗 */}
            {showing && (
              <ManageWorkspace
                hideModal={hideModal}
                providedSlug={selectedWs ? selectedWs.slug : null}
              />
            )}
            {/* 新增，重命名会话弹窗 */}
            {showingSession && (
              <NewSessionModal
                hideModal={hideSessionModal}
                workspaceItem={workspaceItem}
              />
            )}
          </div>
        )}
      </Droppable>
    </DragDropContext>
  );
}

function OptionsMenu({
  containerRef,
  workspace,
  onRemove,
  close,
  currentThreadSlug,
  getWorkspaces = () => {},
}) {
  const [workspaceSet, setWorkspaceSet] = useState(false);
  const [showNameModal, setShowNameModal] = useState(false);
  const [showRemoveModal, setShowRemoveModal] = useState(false);
  const menuRef = useRef(null);
  const hideModal = () => {
    setWorkspaceSet(false);
  };
  const hideNameModal = () => {
    setShowNameModal(false);
  };

  const hideRemoveModal = () => {
    setShowRemoveModal(false);
    close();
  };
  // Ref menu options
  const outsideClick = (e) => {
    if (!menuRef.current) return false;
    if (
      !menuRef.current?.contains(e.target) &&
      !containerRef.current?.contains(e.target)
    )
      close();
    return false;
  };

  const isEsc = (e) => {
    if (e.key === "Escape" || e.key === "Esc") close();
  };

  function cleanupListeners() {
    window.removeEventListener("click", outsideClick);
    window.removeEventListener("keyup", isEsc);
  }
  // end Ref menu options

  useEffect(() => {
    function setListeners() {
      if (!menuRef?.current || !containerRef.current) return false;
      window.document.addEventListener("click", outsideClick);
      window.document.addEventListener("keyup", isEsc);
    }

    setListeners();
    return cleanupListeners;
  }, [menuRef.current, containerRef.current]);

  // 重命名
  const renameThread = async (name) => {
    // const res = await Workspace.threads.update(
    //   workspace.slug,
    //   thread.slug,
    //   name
    // );
    // console.log(res)
    // if (res.message) {
    //   message(`Thread could not be updated! ${message}`);
    //   close();
    //   return;
    // }
    // thread.name = name;
    // close();
    const res = await Workspace.update(workspace.slug, name);
    console.log(res);
    if (res.workspace) {
      message.success("Workspace updated!");
    } else {
      message.error(`Error: ${res.message}`);
      return;
    }
    workspace.name = res.workspace?.name;
    close();
    hideNameModal();
  };

  // 删除
  const handleDelete = async (e) => {
    // e.stopPropagation();
    // onRemove();
    // if (
    //   !window.confirm(
    //     "Are you sure you want to delete this thread? All of its chats will be deleted. You cannot undo this."
    //   )
    // )
    //   return;
    // const success = await Workspace.threads.delete(workspace.slug, thread.slug);
    // if (!success) {
    //   showToast("Thread could not be deleted!", "error", { clear: true });
    //   return;
    // }
    // if (success) {
    //   showToast("Thread deleted successfully!", "success", { clear: true });
    //   onRemove(thread.id);
    //   // Redirect if deleting the active thread
    //   if (currentThreadSlug === thread.slug) {
    //     window.location.href = paths.workspace.chat(workspace.slug);
    //   }
    //   return;
    // }
    const success = await Workspace.delete(workspace.slug);
    console.log(success, "message.errormessage.errormessage.error");
    if (!success) {
      message.error("Workspace could not be deleted!");
      return;
    }
    close();
    hideNameModal();
    getWorkspaces();
    // workspace.slug === slug ? (window.location = paths.home()) : window.location.reload();
  };
  return (
    <>
      <div
        ref={menuRef}
        className="chat-tool w-[160px] absolute w-fit z-[20] top-[25px] right-[10px] bg-zinc-900 rounded-[8px] py-[4px]"
      >
        <button
          onClick={(e) => {
            e.stopPropagation();
            e.preventDefault();
            setShowNameModal(true);
          }}
          type="button"
          className="w-full rounded-[8px] flex items-center px-[12px] py-[8px] gap-x-2 text-slate-300 light:text-theme-text-primary"
        >
          <p className="text-sm tool-text">重命名</p>
        </button>
        <button
          onClick={(e) => {
            e.stopPropagation();
            e.preventDefault();
            setWorkspaceSet(true);
          }}
          type="button"
          className="w-full rounded-[8px] flex items-center px-[12px] py-[8px] gap-x-2 text-slate-300 light:text-theme-text-primary"
        >
          <p className="text-sm tool-text">设置</p>
        </button>
        <button
          onClick={(e) => {
            e.stopPropagation();
            e.preventDefault();
            setShowRemoveModal(true);
          }}
          type="button"
          className="w-full rounded-[8px] flex items-center pl-[12px] py-[8px] gap-x-2 hover:bg-red-500/20 text-slate-300 light:text-theme-text-primary hover:text-red-100"
        >
          <p className="text-sm tool-text">删除</p>
        </button>
      </div>

      <ModalWorkspaceSet
        workspaceSet={workspaceSet}
        hideModal={hideModal}
        close={close}
      />
      {showNameModal && (
        <RenameModals
          hideModal={hideNameModal}
          handleModal={renameThread}
          close={close}
          placeholder="请输入工作区名称"
        />
      )}
      {showRemoveModal && (
        <RemoveModals
          hideModal={hideRemoveModal}
          handleModal={handleDelete}
          close={close}
          title="确定删除该工作区吗？"
          content="删除后AI将无法检索工作区内的文件，源文件将保存在【我的文件】中，此操作不可还原"
        />
      )}
    </>
  );
}
